import cherrypy
from Cheetah.Template import Template
import dailyspents.util as util
from GenericView import GenericView
from dailyspents.model import orm
from dailyspents.controller.UserController import UserController
from dailyspents import _exceptions
from os.path import join

class UserView(GenericView):
    
    def __init__(self):
        GenericView.__init__(self)
        self.userController = UserController()
    
    @cherrypy.expose
    def index(self, message=None, errorMessage=None, page='newuser', **kargs):
        
        self.nameSpace['errorMessage'] = errorMessage
        self.nameSpace['message'] = message
        
        realPage = ''
        
        if page == 'newuser':
            realPage = 'insertUser.html'
            
        elif page == 'edituser':
            self.makeContextMenu()
            realPage = 'editUser.html'
        
        return Template(file=join(util.HTMLPATH, realPage),
                        searchList=[self.nameSpace]).respond()
    
    @cherrypy.expose
    def editUser(self, **kargs):
        try:
            
            name = kargs['name']
            password = kargs['password']
            
            if name.strip() == '' or password.strip() == '':
                msg = 'You must fill the fields: name and password.'
                raise _exceptions.InvalidDataException(msg)
            
            nOfSpent = kargs.get('numberOfSpent', '30')
            
            if not nOfSpent.isdigit():
                msg = 'Field number of shown spent must be all digit.'
                raise _exceptions.InvalidDataException(msg)
            
            user = cherrypy.session['user']
            user.name = name
            user.password = password
            user.settings.numberOfShownSpent = int(nOfSpent)
            user.settings.currency = kargs.get('currency', None)
            
            self.userController.save(user)
            
            cherrypy.session['user'] = user
            
            return self.index(page='edituser', message = 'Item edited sucefully.')
        
        except Exception, e:
            print '[an exception occurred] >>>', e
            return self.index(page='edituser', errorMessage = str(e))
        
    
    @cherrypy.expose                    
    def insertUser(self, **kargs):
        try:
            name = kargs.get('name', '')
            login = kargs.get('login', '')
            password = kargs.get('password', '')
            
            if password.strip() == '' or name.strip() == '' or login.strip() == '':
                msg = 'You must fill the fields: name, login and password.'
                raise _exceptions.InvalidDataException(msg)
            
            user = orm.User()
            user.name = name
            user.login = login
            user.password = password
            
            self.userController.save(user)
            self.message = "User sucefully registered."
            
        except Exception, e:
            raise cherrypy.HTTPRedirect("/user/index?page=newuser&errorMessage="
                                + str(e))
        
        raise cherrypy.HTTPRedirect("/index?message="+self.message)
                 
